import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as API from '../utils/https'
let initialState = {
    table: []
}
const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: {
        t_table(state, action) {
            state.table = action.payload
        },
        t_addtable(state, action) {
            state.table.push(action.payload)
        },
        t_deltable(state, action) {
            state.table = state.table.filter(item.id != action.payload)
        },
        t_edittable(state, action) {
            let index = state.table.findIndex(item => {
                return item.id == action.payload.id
            })
            state.table[index] = action.payload
        },
    },
});

export const todos = todosSlice.actions;
export default todosSlice.reducer;
export let api_table = createAsyncThunk("api_table", async (_, store) => {
    let res = await API.http_table()
    store.dispatch(todos.t_table(res))
})
export let api_addtable = createAsyncThunk("api_addtable", async (obj, store) => {
    let res = await API.http_addtable(obj)
    store.dispatch(todos.t_table(res))
})
export let api_deltable = createAsyncThunk("api_deltable", async (id, store) => {
    await API.http_table(id)
    store.dispatch(todos.t_table(id))
})
export let api_edittable = createAsyncThunk("api_edittable", async (obj, store) => {
    let res = await API.http_edittable(obj)
    console.log(res);
    store.dispatch(todos.t_table(res))
})